import React, { useEffect, useState } from 'react';
import {
  Table, Modal, Form, Input, Col, message, Switch, Select,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import SearchBox from '@/components/SearchBox'
import {
  fetchStaffs,
  fetchSuppliers,
  saveSupplier,
  deleteSupplier,
  getSupplier,
} from '@/services/rentCenter/inverstment';
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils';

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const { Option } = Select

const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
  },
  {
    title: '商户名称',
    key: 'merchantName',
  },
  {
    title: '商户编号',
    key: 'merchantsNum',
  },
  {
    title: '法人',
    key: 'legalPerson',
  },
  {
    title: '法人联系电话',
    key: 'legalPhone',
  },
  {
    title: '招商员',
    key: 'merchantsPerson',
  },
  {
    title: '状态',
    key: 'merchantsStatus',
    render: params => (
      <span>{params.merchantsStatus === '0' ? '意向商户' : '签约商户'}</span>
    ),
  },
  {
    title: '创建时间',
    key: 'createTime',
  },
];

const opratingSupplier = props => {
  const { getFieldDecorator } = props.form;
  const [data, setColData] = useState([]);
  const [record, setRecord] = useState([]);
  const [staffList, setStaffList] = useState([]);
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
  });
  const [info, setInfo] = useState({});
  // 分配\新增角色模态框
  const [isShow, setState] = useState(false);

  // 列表
  const getList = async params => {
    const r = await fetchSuppliers(params);
    if (r.data && r.data.data) {
      setColData(r.data.data);
    }
  };
  useEffect(() => {
    getList(listQuery);
    fetchStaffs({ pageNo: 1, pageSize: 99999 }).then(r => {
      if (r.data && r.data.code === '0') {
        setStaffList(r.data.data)
      }
    })
  }, []);

  // 查询
  const searchOneBtn = async params => {
    getList(params);
  };

  const removeRole = async record => {
    deleteSupplier({
      id: record.id,
    }).then(res => {
      if (res.data.code === '0') {
        const index = data.findIndex(e => e.id === record.id);
        setColData(() => {
          data.splice(index, 1);
          return [...data];
        });
      }
    })
  };
  // 新增/修改 模态框
  const handleStatus = record => {
    setState(!isShow);
    if (record) {
      setInfo(record)
    }
  };
  // 查询表单
  const getFields = () => (
    <Col span={18}>
      <Col span={8}>
        <Form.Item label="商户名称">
          <Input onChange={v => { setListQuery({ ...listQuery, merchantName: v.target.value }) }} placeholder="商户名称" value={listQuery.merchantName} />
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="商户编号">
          <Input onChange={v => { setListQuery({ ...listQuery, merchantNum: v.target.value }) }} placeholder="商户编号" value={listQuery.merchantNum} />
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="法人">
          <Input onChange={v => { setListQuery({ ...listQuery, legalPerson: v.target.value }) }} placeholder="商户法人" value={listQuery.legalPerson} />
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="法人手机">
          <Input onChange={v => { setListQuery({ ...listQuery, legalPhone: v.target.value }) }} placeholder="商户法人手机号码" value={listQuery.legalPhone} />
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="招商员">
          <Input onChange={v => { setListQuery({ ...listQuery, merchantsPerson: v.target.value }) }} placeholder="商户招商员" value={listQuery.merchantsPerson} />
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="状态">
          <Select onChange={v => { setListQuery({ ...listQuery, merchantsStatus: v }) }} placeholder="请选择签约状态" value={listQuery.merchantsStatus}>
            <Option key="1" value="1">签约商户</Option>
            <Option key="0" value="0">意向商户</Option>
          </Select>
        </Form.Item>
      </Col>
    </Col>
  );
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault()
    searchOneBtn(listQuery);
  };

  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const params = values
        params.status ? params.status = '1' : params.status = '0'
        console.log('Received values of form: ', values);
        saveSupplier({ storeBusiness: params }).then(() => {
          getList(listQuery)
          setState(!isShow);
        })
      }
    });
  };
  // 清空查询条件
  const handleReset = () => {
    const aobj = {
      pageNo: 1,
      pageSize: 10,
    }
    setListQuery(aobj)
    getList(aobj)
  };
  // 按钮逻辑
  const handleBtn = type => {
    if (record.length !== 1 && type !== 1) return message.warning('请勾选一条数据！');
    switch (type) {
      // 新增
      case 1:
        return handleStatus();
      // 查询
      case 2:
        return handleSearch();
      case 3:
        return handleStatus(record[0]);
      // 删除
      case 4:
        return removeRole(record[0]);
      default:
        return ''
    }
  };
  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
    },
  };
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table columns={columns} dataSource={hasSearchBtn ? data : data} rowSelection={rowSelection} rowKey={record => record.id} />
      {/* 新增/修改 */}
      <Modal
        title="新增/修改"
        visible={isShow}
        onOk={handleSubmit.bind(this)}
        onCancel={handleStatus.bind(this)}
        destroyOnClose
      >
        <Form {...formItemLayout}>
          <Form.Item label="商户名称">
            {getFieldDecorator('merchantName', {
              initialValue: info.merchantName || '',
              rules: [
                {
                  required: true,
                  message: '请输入商户名称',
                },
              ],
            })(<Input placeholder="请输入商户名称" />)}
          </Form.Item>
          <Form.Item label="商户编号">
            {getFieldDecorator('merchantsNum', {
              initialValue: info.merchantsNum || '',
            })(<Input disabled />)}
          </Form.Item>
          <Form.Item label="法人">
            {getFieldDecorator('legalPerson', {
              initialValue: info.legalPerson || '',
              rules: [
                {
                  required: true,
                  message: '请输入法人',
                },
              ],
            })(<Input placeholder="请输入法人" />)}
          </Form.Item>
          <Form.Item label="身份证号码">
            {getFieldDecorator('legalPersonIdNo', {
              initialValue: info.legalPersonIdNo || '',
              rules: [
                {
                  required: true,
                  message: '请输入身份证号码',
                },
              ],
            })(<Input placeholder="请输入身份证号码" />)}
          </Form.Item>
          <Form.Item label="法人手机">
            {getFieldDecorator('legalPhone', {
              initialValue: info.legalPhone || '',
              rules: [
                {
                  required: true,
                  message: '请输入法人手机',
                },
              ],
            })(<Input placeholder="请输入法人手机" />)}
          </Form.Item>
          <Form.Item label="招商员">
            {getFieldDecorator('staffId', {
              initialValue: info.staffId || '',
              rules: [
                {
                  required: true,
                  message: '请选择招商员',
                },
              ],
            })(<Select placeholder="请选择招商员">{ staffList.map(v => (<Option key={v.id}>{v.name}</Option>)) }</Select>)}
          </Form.Item>
          <Form.Item label="通讯地址">
            {getFieldDecorator('contactAddress', {
              initialValue: info.contactAddress || '',
              rules: [
                {
                  required: true,
                  message: '请输入通讯地址',
                },
              ],
            })(<Input placeholder="请输入通讯地址" />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(opratingSupplier));
